<?php
class GoodsApp extends CommonApp {
   
   	//商品列表
    public function indexAct(){
    	//显示模式(row、cos)
    	$mode = My::arr2var($_COOKIE,'mode');
    	$this->assign('mode',empty($mode) ? 'row' : $mode);
    	
    	$result['type'] = M('admin.category')->item2submenu('goods_type',array('level'=>'1'));
    	$this->assign('result',$result);
		$this->display();
    }
 
 	//商品详情
 	public function detailAct(){
 		$id = My::arr2var($_GET,'id');
 		if(!My::is_id($id))
 			$this->ajaxReturn(404,'id错误！');
 		if(isset($_SESSION['member'])){
 			$member = My::arr2var($_SESSION,'member');
 			$count['bought'] = DB('order')->where("member_id = '{$member['id']}' AND goodsid = '{$id}'")->clear()->count();
 			$this->assign('member',$member);
 			$address_id = DB('address')->where("parent = '{$member['id']}' AND hot = '1' OR parent = '{$member['id']}'")->clear()->getField('id');
			$this->assign('address_id',$address_id);
 		}
 		$count['count'] = DB('order')->where("goodsid = '{$id}'")->clear()->count();
 		$this->assign('count',$count);
		$result = DB('goods')->where("id = '{$id}' AND publish = '1'")->clear()->find();
		$result['params'] = My::decodeJson($result['params']);
		if(strtotime(date('Y-m-d H:i:s')) > strtotime($result['rate']))
			$this->assign('over','over');
		$this->assign('result',$result);
		// setCookie("history_url", $_SERVER["REQUEST_URI"], time()+31536000, "/");
		//设置浏览次数
		DB('datas')->where("id={$id}")->setInc('hit');

		$this->display();
 	}

 	public function goodsAct(){
 		$id = My::arr2var($_GET,'id');
 		if(!My::is_id($id))
 			$this->ajaxReturn(404,'id错误！');
 		$result = DB('goods')->where("id ='{$id}'")->clear()->find();
 		$result['params'] = My::decodeJson($result['params']);
 		$this->assign('result',$result);
 		$this->display();
 	}

 	//处理时间
 	public function getlistAct(){

		$search = array();
    	$search['where'] = "1 ";
    	$search['where'] .= "AND publish=1 ";
    	$search['page'] = My::arr2var($_GET,'page');

    	//按商品类型搜素
    	if(My::is_id(My::arr2var($_GET,'type'))){
			$type = $_GET['type'];
			$search['where'] .= "AND `goods_type`='{$type}' ";
		}

		 //搜索关键字
        $keyword = I('get.keyword');
	    if($keyword!='')
	        $search['where'] .= "AND `title` like '%{$keyword}%' ";

		//根据即将揭晓 人气 最新 价值排序
		$sort = My::arr2var($_GET,'sort');
		$search['order'] = "rate DESC,adddate DESC,id DESC";
		if($sort != ''){
			if($sort == 'adddate')
				$search['order'] = "adddate DESC,id DESC";
			elseif($sort == 'hit')
				$search['order'] = "hit DESC,adddate DESC";
			elseif($sort == 'price'){
				if(My::arr2var($_GET,'order')=='asc') $search['order'] = "price ASC,adddate ASC,id ASC";
				else $search['order'] = "price DESC,adddate DESC,id DESC";
			}
			elseif($sort == 'rate')
				$search['order'] = "rate DESC,adddate DESC,id DESC";
		}

		//获取缓存
		// $html = My::getCache($search,array('pre'=>'goods_list'));
  //   	if($html == ''){
    		$result = DB('goods')->where($search['where'])->order($search['order'])->limit(($search['page']-1)*10,10)->clear()->select();
    		$html='';
    		if($result){
				foreach($result as $key => &$value){
	    		$value['image'] = !empty($value['image']) ? My::thums($value['image'],400,400,true) : My::thums('share/images/default.jpg',400,400,true);
				$html .=<<<HTML
	    		<li class="i_li">
					<a href="index.php?app=Goods&act=detail&id={$value['id']}">
						<div class="img_inner">
							<img src="{$value['image']}">
						</div>
						<div class="cont">
							<p class="i_txt">{$value['title']}</p>
							<div class="price">价值：￥{$value['price']}</div>
							<div class="bom">
								<a onclick="addcart({$value['id']})"><div class="cart"></div></a>
								<a href="javascript:" class="buybtn">立即一元运购</a>
							</div>
						</div>
					</a>
				</li>
HTML;
    			}
    			// My::setCache($search,$html,array('pre'=>'goods_list'));
    			$html = Router::getInstance()->encodeUrls($html);
    		}else
    			$this->ajaxReturn('300','不能加载更多了...');
    		
    	// }
    	$this->ajaxReturn('200',$html);
 	}

 	//支付
 	public function paysAct(){
 		if(!isset($_SESSION['member']))
 			$this->ajaxReturn(201,'请先登陆!');
 		if(empty($_POST['address_id']))
 			$this->ajaxReturn(202,'请先选择收获地址!');
 		$member = array(
			'goodsid' => $_POST['goodsid'],
			'member_id' => $_SESSION['member']['id'],
			'number' => $_POST['total'],
			'istype' => $_POST["istype"],
			'address_id' => $_POST["address_id"],
			);

 		//支付数量
 		if(isset($_POST['buy_type']))
 			$member['buy_type'] = $_POST['buy_type'];

 		$orderuid = implode("-",$member);//此处传入您网站用户的用户名，方便在paysapi后台查看是谁付的款，强烈建议加上。可忽略。

 		//订单号
 		if(isset($_POST['orderids']))
 			$member['orderids'] = explode(',', $_POST['orderids']);
 		//数目
 		if(isset($_POST['price_str']))
 			$member['price_str'] = explode(',', $_POST['price_str']);
 		//保存信息
 		$_SESSION['imforcation'] = $member;
 		// $arr = array('Hello','World!','Beautiful','Day!');echo implode(" ",$arr);
 		//从网页传入price:支付价格， istype:支付渠道：1-支付宝；2-微信支付
	    $price = $_POST["price"];
	    $istype = $_POST["istype"];
	    

	    // $members = explode("-",$orderuid);
	    //校验传入的表单，确保价格为正常价格（整数，1位小数，2位小数都可以），支付渠道只能是1或者2，orderuid长度不要超过33个中英文字。

	    //此处就在您服务器生成新订单，并把创建的订单号传入到下面的orderid中。
	    $goodsname = $_POST["goodsname"];
	    $orderid = $this->createOrderNm();    //每次有任何参数变化，订单号就变一个吧。
	    $uid = "063dca8bfbb303b812a6da71";//"此处填写PaysApi的uid";
	    $token = "246a0dc172176fce3a2277abe4b65d55";//"此处填写PaysApi的Token";
	    $return_url = 'http://srms.telecomlab.cn/ZZX/xuexin/Goods/return_url';
	    $notify_url = 'http://srms.telecomlab.cn/ZZX/xuexin/Goods/notify_url';
	    
	    $key = md5($goodsname. $istype . $notify_url . $orderid . $orderuid . $price . $return_url . $token . $uid);
	    //经常遇到有研发问为啥key值返回错误，大多数原因：1.参数的排列顺序不对；2.上面的参数少传了，但是这里的key值又带进去计算了，导致服务端key算出来和你的不一样。
	    $returndata['goodsname'] = $goodsname;
	    $returndata['istype'] = $istype;
	    $returndata['key'] = $key;
	    $returndata['notify_url'] = $notify_url;
	    $returndata['orderid'] = $orderid;
	    $returndata['orderuid'] =$orderuid;
	    $returndata['price'] = $price;
	    $returndata['return_url'] = $return_url;
	    $returndata['uid'] = $uid;

	    $this->ajaxReturn(200,$returndata);
 	}

 	//用户支付返回界面
 	public function return_urlAct(){
 		if(!$_GET['orderid'])
 			$this->ajaxReturn(404,'支付参数出错');
 		$orderid = $_GET['orderid'];
 		$member = $_SESSION['imforcation'];
 		if(isset($member['buy_type'])){
 			$member['goodsid'] = explode(',', $member['goodsid']);
 			$member['number'] = explode(',', $member['number']);
 			$data['member_id'] = $member['member_id'];
	 		$data['istype'] = $member['istype'];
	 		$data['address_id'] = $member['address_id'];
 			foreach($member['goodsid'] as $key => &$value){
	 			if(isset($member['orderids']))
	 				$data['orderid'] = $member['orderids'][$key];
	 			if(isset($member['price_str']))
	 				$data['price'] = $member['price_str'][$key];
	 			$data['number'] = $member['number'][$key];
	 			$result = DB('order')->where("goodsid = '{$value}' AND orderid = '{$orderid}'")->clear()->save($data);
	 			$result2 = DB('car')->where("goods_id = '{$value}'")->clear()->delete();
	 		}
	 		$orderid_news = $member['orderids'];
	 		$result = array();
	 		foreach($orderid_news as $key => &$value){
	 			$result[$key] = DB('order')->where("orderid = '{$value}'")->clear()->find();
	 		}
 		}else
 			$result['0'] = DB('order')->where("orderid = '{$orderid}'")->clear()->find();
	    //此处在您数据库中查询：此笔订单号是否已经异步通知给您付款成功了。如成功了，就给他返回一个支付成功的展示。
 		unset($_COOKIE['car_number']);
 		$result['address'] = DB('address')->where("id = '{$result['0']['address_id']}'")->find();
	    $this->assign('result',$result);
	    $this->display();
 	}

 	//支付完post参数
 	public function notify_urlAct(){
 		if(!$_POST)
 			$this->ajaxReturn(404,'支付参数出错');
 		$data['paysapi_id'] = $paysapi_id = $_POST["paysapi_id"];//返回的订单号
	    $data['orderid'] = $orderid = $_POST["orderid"];//本服务器生成的订单号
	    $data['price'] = $price = $_POST["price"];//代付金额
	    $data['realprice'] = $realprice = $_POST["realprice"];//已付金额
	    $orderuid = $_POST["orderuid"];//原样返回来的数据
	    $data['adddate'] = date('Y-m-d H:i:s');
	    $key = $_POST["key"];
	    
	    //校验传入的参数是否格式正确，略

	    $token = "246a0dc172176fce3a2277abe4b65d55";
	    
	    $temps = md5($orderid . $orderuid . $paysapi_id . $price . $realprice . $token);

	    if ($temps != $key){
	        return $this->jsonError("key值不匹配");
	    }else{
	    	$members = explode('-', $orderuid);
		    if(!isset($members['5'])){
		    	$data['goodsid'] = $members['0'];
			    $data['member_id'] = $members['1'];
			    $data['number'] = $members['2'];
			    $data['istype'] = $members['3'];
			    $data['address_id'] = $members['4'];
			    $result = DB('order')->clear()->add($data);
		    }else{
		    	$ids = explode(',', $members['0']);
		    	foreach ($ids as $key => &$value) {
		    		$data['goodsid'] = $value;
		    		$result = DB('order')->clear()->add($data);
		    	}
		    }
		    if($result>0)
	    		return $this->jsonSuccess("key值匹配");
	        //校验key成功，是自己人。执行自己的业务逻辑：加余额，订单付款成功，装备购买成功等等。
	        
	    }
 	}

 	//返回错误
    function jsonError($message = '',$url=null) 
    {
        $return['msg'] = $message;
        $return['data'] = '';
        $return['code'] = -1;
        $return['url'] = $url;
        return json_encode($return);
    }

    //返回正确
    function jsonSuccess($message = '',$data = '',$url=null) 
    {
        $return['msg']  = $message;
        $return['data'] = $data;
        $return['code'] = 1;
        $return['url'] = $url;
        return json_encode($return);
    }


}